import { formAdd, formEdit } from "@/services/formInteraction";
import { Form, Input, Modal, Select, message } from "antd";
import React from "react";

class CreateModal extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      visible:false,
      info:{}
    }
  }

  componentDidMount(){
    if(this.props.onRef){
      this.props.onRef(this)
    }
  }

  initModal = row => {
    this.setState({
      visible:true,
      info:row ? row : {}
    })
  }

  cancelModal = () => {
    this.props.form.resetFields()
    this.setState({
      visible:false,
      info:{}
    })
  }

  doValidate = () => {
    this.props.form.validateFields((error,values) => {
      if(!error){
        this.doOk(values)
      }
    })
  }

  doOk = async values => {
    let res = {}
    const { info } = this.state;
    if(info.id){
      values.id = info.id
      res = await formEdit(values)
    }else{
      res = await formAdd(values)
    }

    message.info(res.message)
    this.cancelModal()
    this.props.refreshList()
  }

  render(){
    const { visible,info } = this.state;
    const { form:{getFieldDecorator,getFieldValue},tabId,tabPaneList } = this.props;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 },
      },
    };
    return (
      <Modal
        title={info.id ? '编辑场景名称和描述' :"创建场景"}
        visible={visible}
        onCancel={this.cancelModal}
        onOk={this.doValidate}
      >
        <Form {...formItemLayout}>
          <Form.Item label="表单名称">
            {
              getFieldDecorator("name",{
                rules:[{required:true,message:"表单名称必填"}],
                initialValue:info.name
              })(
                <Input placeholder="请输入场景名称" />
              )
            }
          </Form.Item>
          <Form.Item label='表单分类'>
            {getFieldDecorator("categoryId", {
              rules: [{ required: true, message: "表单分类必填" }],
              initialValue: tabId,
            })(
              <Select>
                {tabPaneList.map((item) => {
                  return (
                    <Select.Option value={item.id} key={item.id}>
                      {item.name}
                    </Select.Option>
                  );
                })}
              </Select>
            )}
          </Form.Item>
        </Form>
      </Modal>
    )
  }
}

export default Form.create()(CreateModal)